<?php


namespace app\api\model;


use app\common\library\IDMan;
use app\common\library\PlatformModel;
use app\common\library\StatModel;
use app\common\model\BaseModel;
use common;
use think\facade\Log;

class UserMembershipOrderModel extends BaseModel
{
    protected $name = 'user_membership_order';
    protected $pk = 'id';

    var $members_cards = [
        [
            'id' => 1,
            'name' => '30天会员卡',
            'price' => 990, //690
            'duration' => 24 * 30 * 3600,
        ],
        [
            'id' => 2,
            'name' => '90天会员卡',
            'price' => 2480, //990
            'duration' => 3 * 24 * 30 * 3600,
        ],
        [
            'id' => 3,
            'name' => '360天会员卡',
            'price' => 9980, //2990
            'duration' => 12 * 24 * 30 * 3600,
        ],
    ];

    var $members_cards_cheep = [
        [
            'id' => 1,
            'name' => '30天会员卡',
            'price' => 690, //690
            'duration' => 24 * 30 * 3600,
        ],
        [
            'id' => 2,
            'name' => '90天会员卡',
            'price' => 990, //990
            'duration' => 3 * 24 * 30 * 3600,
        ],
        [
            'id' => 3,
            'name' => '360天会员卡',
            'price' => 2990, //2990
            'duration' => 12 * 24 * 30 * 3600,
        ],
    ];

    function __construct()
    {
        global $g_env;
        if ($g_env != 'ONLINE') {
            $this->members_cards[] = [
                'id' => 4,
                'name' => '1天会员卡',
                'price' => 1, //2990
                'duration' => 24 * 3600,
            ];
        }
    }

    function card_list($city_id)
    {
        if ($city_id == '350800'|| $city_id =='451100'){
            return $this->members_cards;
        }
//        else if ($city_id == '350002'){
//            return [];
//        }
        else
            return $this->members_cards_cheep;
    }

    function query_card_info($id,$city_id)
    {
        if ($city_id == '350800' || $city_id == '451100') {
            foreach ($this->members_cards as $info) {
                if ($info['id'] == $id) {
                    return $info;
                }
            }
        }
        else{
            foreach ($this->members_cards_cheep as $info) {
                if ($info['id'] == $id) {
                    return $info;
                }
            }
        }

        return null;
    }

    function submit_wxmp($city_id, $userinfo, $card_id)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }


        $card_info = $this->query_card_info($card_id,$city_id);
        if (empty($card_info)) {
            $this->throw_myexception(X_ERROR, "查询会员卡失败!");
        }

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxmp_unifield_order($city_id, ORDER_TYPE_USER_MEMBER_SHIP, $order_id, $card_info['price'], $card_info['name'],$pay_city);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }

        $platform = (new PlatformModel())->get_platform_info('wxmpu');


        $prepay_info = [
            'appId' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepay_id'],
            'nonceStr' => uniqid(),
            'timeStamp' => time(),
            'signType' => 'MD5',
        ];

        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        //$prepay_info['mch_id'] = $ret['mch_id'];
        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'pay_city' =>$pay_city,
        ];

        self::create($order_info);
        return $prepay_info;
    }


    function submit_wxapp($city_id, $userinfo, $card_id)
    {
        $card_info = $this->query_card_info($card_id,$city_id);
        if (empty($card_info)) {
            $this->throw_myexception(X_ERROR, "查询会员卡失败!");
        }

        $order_id = IDMan::order_id();
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }
        $ret = (new PayModel($pay_city))->wxapp_unifield_order($city_id, ORDER_TYPE_USER_MEMBER_SHIP, $order_id, $card_info['price'], $card_info['name'],$pay_city);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }

        $platform = (new PlatformModel())->get_platform_info('wxapp');

        $prepay_info = [
            'appid' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepayid'],
            'noncestr' => uniqid(),
            'timestamp' => time(),
            'prepayid' => $ret['prepayid'],
            'partnerid' => $ret['partnerid'],
        ];


        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        $prepay_info['mch_id'] = $ret['mch_id'];
        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'pay_city' =>$pay_city,
        ];

        self::create($order_info);
        return $prepay_info;
    }


    function submit_alipay($city_id, $userinfo, $card_id)
    {
        $card_info = $this->query_card_info($card_id,$city_id);
        if (empty($card_info)) {
            $this->throw_myexception(X_ERROR, "查询会员卡失败!");
        }

        $alipay_user_id = $userinfo['alipay_user_id'];

        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade($city_id, ORDER_TYPE_USER_MEMBER_SHIP, $order_id, $alipay_user_id, $card_info['price'], $card_info['name']);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_ALIPAY,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'pay_city' => $pay_city,
        ];




        self::create($order_info);
        return $ret;
    }

    function submit_aliapp($city_id, $userinfo, $card_id)
    {
        $card_info = $this->query_card_info($card_id,$city_id);
        if (empty($card_info)) {
            $this->throw_myexception(X_ERROR, "查询会员卡失败!");
        }

        $alipay_user_id = $userinfo['alipay_user_id'];

        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade_app($city_id, ORDER_TYPE_USER_MEMBER_SHIP, $order_id, $card_info['price'], $card_info['name']);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_ALIPAY,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'pay_city' => $pay_city,
        ];




        self::create($order_info);
        return $ret;
    }

    function gift_week_membership($userinfo)
    {
        $card_info = [
            'id' => 0,
            'name' => '赠送30天会员卡',
            'price' => 0,
            'duration' => 24 * 30 * 3600,
        ];

        $order_id = IDMan::order_id();

        $membership_start_time = null;
        $membership_expire_time = null;
        if (empty($userinfo['membership_expire_time']) || $userinfo['membership_expire_time'] < date('Y-m-d H:i:s')) {
            $membership_start_time = date('Y-m-d H:i:s');
            $membership_expire_time = date('Y-m-d H:i:s', time() + $card_info['duration']);
        } else {
            $membership_start_time = $userinfo['membership_expire_time'];
            $membership_expire_time = date('Y-m-d H:i:s', strtotime($userinfo['membership_expire_time']) + $card_info['duration']);
        }
        (new UserModel())->set_membership_expire_time($userinfo['id'], $membership_expire_time);

        $order_info = [
            'id' => $order_id,
            'city_id'=>$userinfo['city_id'],
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_FEE,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => [],
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_expire_time,
        ];

        self::create($order_info);
    }

    function finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_MEMBERSHIP_ORDER_STATE_SUBMIT) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        $userinfo = (new UserModel())->query_info($order_info['user_id']);
        $membership_start_time = null;
        $membership_expire_time = null;
        if (empty($userinfo['membership_expire_time']) || $userinfo['membership_expire_time'] < date('Y-m-d H:i:s')) {
            $membership_start_time = date('Y-m-d H:i:s');
            $membership_expire_time = date('Y-m-d H:i:s', time() + $order_info['duration']);
        } else {
            $membership_start_time = $userinfo['membership_expire_time'];
            $membership_expire_time = date('Y-m-d H:i:s', strtotime($userinfo['membership_expire_time']) + $order_info['duration']);
        }
        (new UserModel())->set_membership_expire_time($order_info['user_id'], $membership_expire_time);

        $data = [
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => $payment_info,
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_expire_time,
        ];
        $where = [
            'id' => $order_id,
        ];
        self::update($data, $where);

        (new StatModel())->user_membership_order_amount_incr($order_info['city_id'], $order_info['amount']);
        (new StatNewModel())->user_membership_incr($order_info['city_id'], floor($order_info['duration'] / 86400), $order_info['amount'], date('Y-m-d'));
    }

    function query_info($order_id)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            //  'payment_info' => 'array',
            //  'end_time' => 'string',
            'duration' => 'int',
            'membership_start_time' => 'string',
            'membership_end_time' => 'string',
            'membership_card_id' => 'int',
            'membership_card_name' => 'string',
            'refund_order_id' => 'string',
            'refund_amount' => 'int',
            'pay_city' => 'string',
        ];

        $sfs = common::array_keys($selectlist);
        $beans = [
            'id'=>$order_id,
        ];
        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }

    function query_my_list($cd, $pos, $limit)
    {
        $selectlist = [
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            // 'payment_info' => 'array',
            'end_time' => 'string',
            'membership_start_time' => 'string',
            'membership_end_time' => 'string',
            'membership_card_id' => 'int',
            'membership_card_name' => 'string',
            'refund_order_id' => 'string',
            'refund_amount' => 'int',
            'free' =>'int',
        ];

        $sfs = common::array_keys($selectlist);
        $datenow = date('Y-m-d H:i:s');
        $beans = [
            'membership_end_time' => ['>',$datenow],
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED
        ];
        if (isset($cd['user_id'])) {
            $beans['user_id'] = $cd['user_id'];
        }


        $rows  = $this->where($beans)->field($sfs)->order('create_time','desc')->limit($pos,$limit)->select();

        return $rows->toArray();
    }

    function query_list($city_id, $cd, $pos, $limit)
    {
        $limit = min(30, $limit);
        $selectlist = [
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            //'payment_info' => 'array',
            'end_time' => 'string',
            'membership_start_time' => 'string',
            'membership_end_time' => 'string',
            'membership_card_id' => 'int',
            'membership_card_name' => 'string',
            'refund_order_id' => 'string',
            'refund_amount' => 'int',
            'free' => 'int',
        ];

        $sfs = common::array_keys($selectlist);
        $beans = [
        ];
        if (!empty($city_id)) {
            $beans['city_id'] = $city_id;
        }

        if (isset($cd['user_id'])) {
            $beans['user_id'] = $cd['user_id'];
        }
        $beans['order_state'] = ['>=',USER_MEMBERSHIP_ORDER_STATE_FINISHED];

        $rows  = $this->where($beans)->field($sfs)->order('create_time','desc')->limit($pos,$limit)->select();

        return $rows->toArray();
    }

    function summit_refund($order_id, $amount, $reason)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单信息失败！");
        }

        if ($order_info['order_state'] != USER_MEMBERSHIP_ORDER_STATE_FINISHED) {
            $this->throw_myexception(ERROR_QUERY_INFO, "未完成支付订单！");
        }

        $pay_city = 'default';
        if (!empty($order_info['pay_city'])){
            $pay_city = $order_info['pay_city'];
        }

        $ret = (new PayModel($pay_city))->submit_refund($order_id, ORDER_TYPE_USER_MEMBER_SHIP_REFUND, $amount, $reason);
        if ($ret) {
            $data = [
                'order_state' => USER_MEMBERSHIP_ORDER_STATE_REFUND,
                'refund_order_id' => $ret->order_id,
                'refund_amount' => $amount,
            ];

            if ($ret->order_state == PAY_ORDER_STATE_REFUND_FINISH) {
                $data['payment_info'] = $ret;
                $data['end_time'] = date('Y-m-d H:i:s');
                $data['order_state'] = USER_MEMBERSHIP_ORDER_STATE_REFUND_FINISHED;
            }
            $where = [
                'id' => $order_id,
            ];

            self::update($data, $where);

            $userinfo = (new UserModel())->query_info($order_info['user_id']);
            $expire_time = $userinfo['membership_expire_time'];
            if (!empty($expire_time)) {
                $expire_time = date('Y-m-d H:i:s', strtotime($expire_time) - $order_info['duration']);
            }
            if ($expire_time <= date('Y-m-d H:i:s')) {
                $expire_time = null;
            }

            (new UserModel())->set_membership_expire_time($userinfo['id'], $expire_time);
            $log = "用户免押金退款：{$userinfo['name']}, {$userinfo['phone']} 发起退款，订单id：{$order_id}}, 金额: {$amount}, 过期时间:{$expire_time}";
            Log::debug($log);
        }

    }

    function refund_finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_MEMBERSHIP_ORDER_STATE_REFUND) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        $data = [
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_REFUND_FINISHED,
            'end_time' => date('Y-m-d H:i:s'),
        ];
        if ($payment_info) {
            $data['payment_info'] = $payment_info;
        }

        $where = [
            'id' => $order_id,
        ];

        self::update($data, $where);
    }

    function gift_day_membership($userinfo, $days)
    {
        $card_info = [
            'id' => 0,
            'name' => $days . '天会员卡',
            'price' => 0,
            'duration' => 24 * $days * 3600,
        ];

        $order_id = IDMan::order_id();

        $membership_start_time = date('Y-m-d H:i:s');
        if(isset($userinfo['membership_expire_time']) && $userinfo['membership_expire_time'] > $membership_start_time){
            $membership_start_time = $userinfo['membership_expire_time'];
        }
        $membership_end_time = date('Y-m-d H:i:s', strtotime($membership_start_time)+$card_info['duration']);

        $order_info = [
            'id' => $order_id,
            'city_id' => $userinfo['city_id'],
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_PRESENT,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => [],
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_end_time,
        ];

        self::create($order_info);
        return $membership_end_time;
    }

    function add_free_membership($userinfo)
    {
        $card_info = [
            'id' => 0,
            'name' => '战疫天使卡',
            'price' => 0,
            'duration' => 24 * 365 * 3600,
            'free'=>1,
        ];

        $order_id = IDMan::order_id();

        $membership_start_time = date('Y-m-d H:i:s');
        if(isset($userinfo['membership_expire_time']) && $userinfo['membership_expire_time'] > $membership_start_time){
            $membership_start_time = $userinfo['membership_expire_time'];
        }
        $membership_end_time = date('Y-m-d H:i:s', strtotime($membership_start_time)+$card_info['duration']);

        $order_info = [
            'id' => $order_id,
            'city_id' => $userinfo['city_id'],
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_PRESENT,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => [],
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_end_time,
            'free' => $card_info['free'],
        ];

        self::create($order_info);
        return $membership_end_time;
    }

    function add_lucky_membership($userinfo,$day)
    {
        $duration = $day * 24 *3600;
        $card_info = [
            'id' => 0,
            'name' => '锦鲤幸运卡',
            'price' => 0,
            'duration' => $duration,
            'free'=>2,
        ];

        $order_id = IDMan::order_id();

        $membership_start_time = date('Y-m-d H:i:s');
        if(isset($userinfo['membership_expire_time']) && $userinfo['membership_expire_time'] > $membership_start_time){
            $membership_start_time = $userinfo['membership_expire_time'];
        }
        $membership_end_time = date('Y-m-d H:i:s', strtotime($membership_start_time)+$card_info['duration']);

        $order_info = [
            'id' => $order_id,
            'city_id' => $userinfo['city_id'],
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_PRESENT,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => [],
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_end_time,
            'free' => $card_info['free'],
        ];

        self::create($order_info);
        return $membership_end_time;
    }

    function add_day_membership($userinfo, $name,$duration,$gate_way)
    {
        $card_info = [
            'id' => 0,
            'name' => $name,
            'price' => 0,
            'duration' => $duration,
        ];

        $order_id = IDMan::order_id();

        $membership_start_time = date('Y-m-d H:i:s');
        if(isset($userinfo['membership_expire_time']) && $userinfo['membership_expire_time'] > $membership_start_time){
            $membership_start_time = $userinfo['membership_expire_time'];
        }
        $membership_end_time = date('Y-m-d H:i:s', strtotime($membership_start_time)+$card_info['duration']);

        $order_info = [
            'id' => $order_id,
            'city_id' => $userinfo['city_id'],
            'amount' => $card_info['price'],
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            'gateway' => $gate_way,
            'duration' => $card_info['duration'],
            'membership_card_id' => $card_info['id'],
            'membership_card_name' => $card_info['name'],
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => [],
            'membership_start_time' => $membership_start_time,
            'membership_end_time' => $membership_end_time,
        ];

        self::create($order_info);
        return $membership_end_time;
    }
}